namespace Wiki.IO
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.Mvc;
    using System.Xml;

    using Wiki.Security.Cryptography;

    public sealed class WrappedStream : Stream
    {
        private static readonly Regex HtmlWhitespaceRegex = new Regex(@"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[\n])\s{2,}");

        public WrappedStream(Stream stream)
        {
            if (null == stream)
            {
                throw new ArgumentNullException("stream");
            }

            this.UnderlyingStream = stream;
            this.Bytes = new List<byte>();
        }

        public override bool CanRead
        {
            get
            {
                return this.UnderlyingStream.CanRead;
            }
        }

        public override bool CanSeek
        {
            get
            {
                return this.UnderlyingStream.CanSeek;
            }
        }

        public override bool CanWrite
        {
            get
            {
                return this.UnderlyingStream.CanWrite;
            }
        }

        public override long Length
        {
            get
            {
                return this.UnderlyingStream.Length;
            }
        }

        public override long Position
        {
            get
            {
                return this.UnderlyingStream.Position;
            }

            set
            {
                this.UnderlyingStream.Position = value;
            }
        }

        public string ContentMD5
        {
            get
            {
                return MD5Digest.Calculate(this.Bytes.ToArray());
            }
        }

        private List<byte> Bytes { get; set; }

        private Stream UnderlyingStream { get; set; }

        public override void Flush()
        {
            this.UnderlyingStream.Flush();
            this.Bytes = new List<byte>();
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return this.UnderlyingStream.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return this.UnderlyingStream.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            this.UnderlyingStream.SetLength(value);
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            if (null != HttpContext.Current)
            {
                HttpResponse response = HttpContext.Current.Response;
                if (response.ContentType.StartsWith("text/html", StringComparison.OrdinalIgnoreCase) || response.ContentType.StartsWith("application/xhtml+xml", StringComparison.OrdinalIgnoreCase))
                {
                    buffer = response.ContentEncoding.GetBytes(HtmlWhitespaceRegex.Replace(response.ContentEncoding.GetString(buffer), String.Empty));
                }
            }

            this.UnderlyingStream.Write(buffer, offset, buffer.Length);

            if (this.Bytes.Count == offset)
            {
                this.Bytes.AddRange(buffer);
            }
            else
            {
                for (int i = 0; i < buffer.Length; i++)
                {
                    this.Bytes[offset + i] = buffer[i];
                }
            }
        }
    }
}